import React, { PureComponent } from 'react'
import {
  Card,
  Icon,
  Form,
  Input,
  Cascader,
  Button,
  message
} from 'antd'

import LinkButton from '../../components/LinkButton'
import PicturesWall from '../../components/PicturesWall/PicturesWall'
import RichTextEditor from '../../components/RichTextEditor/RichTextEditor'
import { reqCategories, reqAddOrUpdateProduct } from '../../api'

const { Item } = Form
const { TextArea } = Input

// Product 的更新子路由组件
class ProductAddUpdate extends PureComponent {
  constructor (props) {
    super(props)

    // 创建用来保存 ref 标识的标签对象的容器
    this.pw = React.createRef()
    this.editor = React.createRef()
  }

  state = {
    options: [],
  }

  initOptions = async (categories) => {
    // 根据 categories 生成 options 数组
    const options = categories.map(c => ({
      value: c._id,
      label: c.name,
      isLeaf: false
    }))

    // 如果是一个二级分类商品的更新
    const { isUpdate, product } = this
    const { pCategoryId }  = product
    if (isUpdate && pCategoryId !== '0') {
      // 获取对应的二级分类列表
      const subCategories = await this.getCategories(pCategoryId)
      // 生成二级下拉列表, options
      const childOptions = subCategories.map(c => ({
        value: c._id,
        label: c.name,
        isLeaf: true
      }))

      const targetOption = options.find(option => option.value === pCategoryId)

      // 关联到对应的 一级options上
      targetOption.children = childOptions
    }

    // 更新 options 状态
    this.setState({ options })
  }

  // 异步获取一级/二级分类列表, 并显示
  getCategories = async (parentId) => {
    const result = await reqCategories(parentId)
    if (result.status === 0) {
      const categories = result.data
      // 判断是否为一级分类列表还是二级列表
      if (parentId === '0') { // 一级列表
        this.initOptions(categories)
      } else { // 二级列表
        return categories // 返回二级列表 --> 当前 async 函数返回的 promise就会成功且value值为 categories
      }
    }
  }

  // 初始化 Item 布局的配置对象
  initFormItemLayout = () => {
    this.formItemLayout = {
      labelCol: { // 左侧 label 的宽度
        xs: { span: 24 },
        sm: { span: 2},
      },
      wrapperCol: { // 右侧包裹的宽度
        xs: { span: 24 },
        sm: { span: 8 },
      },
    }
  }

  // 提交表单, 发送请求
  submit = () => {
    // 进行表单验证, 如果通过, 才发送请求
    this.props.form.validateFields(async (err, values) => {
      if (!err) {
        // console.log(values)
        // 1. 收集数据, 并封装为 product 对象
        const imgs = this.pw.current.getImgs()
        const detail = this.editor.current.getDetail()
        const { name, desc, price, categoryIds } = values
        let pCategoryId, categoryId
        if (categoryIds.length === 1) {
          pCategoryId = '0'
          categoryId = categoryIds[0]
        } else {
          pCategoryId = categoryIds[0]
          categoryId = categoryIds[1]
        }
        const product = { name, desc, price, imgs, detail, pCategoryId, categoryId }

        // 如果是更新, 需要添加 _id,
        if (this.isUpdate) {
          product._id = this.product._id
        }

        // 2. 调用接口请求函数去添加/更新
        const result = await reqAddOrUpdateProduct(product)

        // 3. 根据结果提示信息
        if (result.status === 0) {
          message.success(`${this.isUpdate ? '更新' : '添加'}商品成功`)
          this.props.history.goBack()
        } else {
          message.error(`${this.isUpdate ? '更新' : '添加'}商品失败`)
        }
      }
    })
  }

  // 自定义商品价格验证
  validatePrice = (rule, value, callback) => {
    if (value * 1 > 0) {
      callback()
    } else {
      callback('价格必须大于0')
    }
  }

  loadData = async selectedOptions => {
    const targetOption = selectedOptions[selectedOptions.length - 1]
    targetOption.loading = true

    // 根据选中的分类, 请求获取二级分类列表
    const subCategories = await this.getCategories(targetOption.value)
    targetOption.loading = false
    if (subCategories && subCategories.length > 0) {
      // 生成一个二级列表的 options
      const subOptions = subCategories.map(c => ({
        value: c._id,
        label: c.name,
        isLeaf: true
      }))
      // 关联到当前的 options 上
      targetOption.children = subOptions
    } else { // 当前选中的分类没有二级分类
      targetOption.isLeaf = true
    }

    // 更新 options 状态
    this.setState({
      options: [...this.state.options]
    })
  }

  UNSAFE_componentWillMount () {
    this.initFormItemLayout()

    // 取出携带的 state
    const product = this.props.location.state // 如果是添加, 则没值
    // 保存是否是更新的标识
    this.isUpdate = !!product
    // 保存商品, 如果没有, 就为 {}
    this.product = product || {}
  }

  componentDidMount () {
    this.getCategories('0')
  }

  render () {
    const { options } = this.state
    const { isUpdate, product } = this

    const { categoryId, pCategoryId, imgs, detail } = product
    // 用来接收级联分类 id 的数组
    const categoryIds = []
    if (isUpdate) {
      // 商品是一个一级分类数组
      if (pCategoryId === '0') {
        categoryIds.push(categoryId)
      } else {
        // 商品是一个二级分类数组
        categoryIds.push(pCategoryId)
        categoryIds.push(categoryId)
      }
    }

    const title = (
      <span>
        <LinkButton onClick={() => this.props.history.goBack()}>
          <Icon type='arrow-left' style={{fontSize: 20}} />
        </LinkButton>
        <span>{ isUpdate ? '修改商品' : '添加商品'}</span>
      </span>
    )

    const { getFieldDecorator } = this.props.form

    return (
      <Card title={title}>
        <Form {...this.formItemLayout}>
          <Item label="商品名称">
            {
              getFieldDecorator('name', {
                initialValue: product.name,
                rules: [{ required: true, message: '必须输入商品名称' }]
              })(
                <Input placeholder='请输入商品名称' />
              )
            }
          </Item>
          <Item label="商品描述">
            {
              getFieldDecorator('desc', {
                initialValue: product.desc,
                rules: [{ required: true, message: '必须输入商品描述' }]
              })(
                <TextArea placeholder="请输入商品描述" autosize={{ minRows: 2, maxRows: 8}} />
              )
            }
          </Item>
          <Item label="商品价格">
            {
              getFieldDecorator('price', {
                initialValue: product.price,
                rules: [
                  { required: true, message: '必须输入商品价格' },
                  { validator: this.validatePrice }
              ],
              })(
                <Input addonAfter='元' type='number' placeholder='请输入商品价格' />
              )
            }
          </Item>
          <Item label="商品分类">
            {
              getFieldDecorator('categoryIds', {
                initialValue: categoryIds,
                rules: [
                  { required: true, message: '必须输入商品分类' }
                ],
              })(
                <Cascader
                  options={options}
                  loadData={this.loadData}
                />
              )
            }

          </Item>
          <Item label="商品图片">
            <PicturesWall ref={this.pw} imgs={imgs} />
          </Item>
          <Item label="商品详情" labelCol={{span: 2}} wrapperCol={{span: 20}}>
            <RichTextEditor ref={this.editor} detail={detail} />
          </Item>
          <Item>
            <Button type='primary' onClick={this.submit}>提交</Button>
          </Item>
        </Form>
      </Card>
    )
  }
}

export default Form.create()(ProductAddUpdate)
